/**	
 * Author : Mht
 * Desc : For 2016 RDM 
 */
package common;

import java.security.MessageDigest;
import java.util.Arrays;

import lombok.extern.log4j.Log4j;

/**
 * @author Mht
 * @date May 27, 2016
 */
@Log4j
public class SignUtil {

	private final static String TOKEN = "WeChat";

	/**
	 * 验证签名
	 */
	public static boolean checkSignature(String signature, String timestamp, String nonce) {
		String[] arrs = new String[] { TOKEN, timestamp, nonce };
		Arrays.sort(arrs);
		StringBuffer content = new StringBuffer();
		for (String arr : arrs) {
			content.append(arr);
		}
		MessageDigest md = null;
		String tempStr = "";
		try {
			md = MessageDigest.getInstance("SHA-1");
			byte[] digests = md.digest(content.toString().getBytes());
			tempStr = byteToString(digests);
		} catch (Exception e) {
			log.error("Digest Failed : " + e.getMessage());
		}
		log.info(String.format("[Signature = %s,Digest = %s]", signature, tempStr));
		return null != tempStr ? tempStr.equals(signature.toUpperCase()) : false;
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 */
	private static String byteToString(byte[] byteArray) {
		String strDigest = "";
		for (byte bt : byteArray) {
			strDigest += byteToHexStr(bt);
		}
		return strDigest;
	}

	/**
	 * 将字节转换为十六进制字符串
	 */
	private static String byteToHexStr(byte b) {
		char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = digit[(b >>> 4) & 0X0F];
		tempArr[1] = digit[b & 0X0F];
		return new String(tempArr);
	}
}
